//
//  NSString+Common.m
//  Randomdoor
//
//  Created by ff on 2022/8/9.
//

#import "NSString+FMCommon.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation NSString (FMCommon)

-(BOOL)isBlankString{
       if(self == nil) {
            return YES;
        }
        if (self == NULL) {
            return YES;
        }
        if ([self isKindOfClass:[NSNull class]]) {
            return YES;
        }
        if ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
            return YES;
        }
    return NO;

}

- (NSAttributedString *)attributedStringWithHTMLString
{
    NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
    NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };
    NSString *str = [NSString stringWithFormat:@"<head><style>img{width:%f !important;height:auto}</style></head>%@",WIDTH ,self];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
    
    return attributeString;
}

-(NSString *)componentsWithStr{
    
    if (self.length > 0) {
        return  [self substringWithRange:NSMakeRange(5, 11)];
    }else{
        return  @"";
    }
}

-(BOOL )timeWithResultTime{
    
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSString *currentDateStr = [dateFormatter stringFromDate:currentDate];
    BOOL result = [self compare:currentDateStr] == NSOrderedAscending;
    
    return result;
}

-(NSString *)stringTranscoding{
    
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                                    (CFStringRef)self,
                                                                                                    (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                                                                    NULL,
                                                                                                    kCFStringEncodingUTF8));
    return encodedString;
    
}

-(NSString *)urlWithLayout{
    
    NSString *headerString = @"<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>";
        NSString *adaptString = [NSString stringWithFormat:@"<head><style>img{max-width:100%% !important;height:auto !important}</style></head>%@", [NSString stringWithFormat:@"%@<br><br>", self]];
        NSString * path = [headerString stringByAppendingString:adaptString];
    return path;
}

+ (CGFloat)getStringHeightWithText:(NSString *)text font:(UIFont *)font viewWidth:(CGFloat)width {
    // 设置文字属性 要和label的一致
    NSDictionary *attrs = @{NSFontAttributeName :font};
    CGSize maxSize = CGSizeMake(width, MAXFLOAT);
    
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    
    // 计算文字占据的宽高
    CGSize size = [text boundingRectWithSize:maxSize options:options attributes:attrs context:nil].size;
    
    // 当你是把获得的高度来布局控件的View的高度的时候.size转化为ceilf(size.height)。
    return  ceilf(size.height);
}

+ (CGFloat)getStringWidthWithText:(NSString *)text font:(UIFont *)font viewHeight:(CGFloat)height {
    // 设置文字属性 要和label的一致
    NSDictionary *attrs = @{NSFontAttributeName :font};
    CGSize maxSize = CGSizeMake(MAXFLOAT, height);
    
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    
    // 计算文字占据的宽高
    CGSize size = [text boundingRectWithSize:maxSize options:options attributes:attrs context:nil].size;
    
    // 当你是把获得的高度来布局控件的View的高度的时候.size转化为ceilf(size.height)。
    return  ceilf(size.width);
}

+ (NSMutableAttributedString *)getHtmlStringWithString:(NSString *)string {
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                              NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding)};
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
    // 设置段落格式
    NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc] init];
    para.lineSpacing = 8;
    [attStr addAttribute:NSParagraphStyleAttributeName value:para range:NSMakeRange(0, attStr.length)];
    // 设置文本的Font
    [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, attStr.length)];
    [attStr addAttribute:NSForegroundColorAttributeName value:RDRGB(0x333333) range:NSMakeRange(0, attStr.length)];
    return attStr;
}

-(NSString *)getPersonalityDateFormat{
    
    NSString *time = [self getTimeStrWithString:self];
    
    return [self timeWithYearMonthDayCountDown:time];
}


-(NSString*)getTimeStrWithString:(NSString*)str{
    NSDateFormatter*dateFormatter=[[NSDateFormatter alloc]init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];//设定时间的格式
    NSDate*tempDate=[dateFormatter dateFromString:str];//将字符串转换为时间对象
    NSString*timeStr=[NSString stringWithFormat:@"%ld",(long)[tempDate timeIntervalSince1970]*1000];//字符串转成时间戳,精确到毫秒*1000
    return timeStr;
}

-(NSString*)timeWithYearMonthDayCountDown:(NSString*)timestamp{// 时间戳转日期// 传入的时间戳timeStr如果是精确到毫秒的记得要/1000
    NSTimeInterval timeInterval=[timestamp doubleValue]/1000;
    NSDate*detailDate=[NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter*dateFormatter=[[NSDateFormatter alloc]init];// 实例化一个NSDateFormatter对象，设定时间格式，这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"MM-dd HH:mm"];
    NSString*dateStr=[dateFormatter stringFromDate:detailDate];
    return dateStr;
}

+ (NSString *)currentTimeStr{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
//    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; //
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
}

#pragma mark - 散列函数
- (NSString *)md5String {
    const char *str = self.UTF8String;
    
    uint8_t buffer[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(str, (CC_LONG)strlen(str), buffer);
    
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH ];
       for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
           [digest appendFormat:@"%02X", buffer[i]];
       }
    
    return digest;
}


/**
 *  返回二进制 Bytes 流的字符串表示形式
 *
 *  @param bytes  二进制 Bytes 数组
 *  @param length 数组长度
 *
 *  @return 字符串表示形式
 */
- (NSString *)stringFromBytes:(uint8_t *)bytes length:(int)length {
    NSMutableString *strM = [NSMutableString string];
    
    for (int i = 0; i < length; i++) {
        [strM appendFormat:@"%02x", bytes[i]];
    }
    
    return [strM copy];
}

-(BOOL)containsAlphabetAndNumber {
    if (!self || [self length] == 0) {
        return NO;
    }
    
    NSCharacterSet *alphabetSet = [NSCharacterSet alphanumericCharacterSet];
    NSCharacterSet *letterSet = [NSCharacterSet letterCharacterSet];
    NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet];
    
    BOOL hasLetter = NO;
    BOOL hasNumber = NO;
    
    for (NSUInteger i = 0; i < [self length]; i++) {
        unichar character = [self characterAtIndex:i];
        
        if ([alphabetSet characterIsMember:character]) {
            if ([letterSet characterIsMember:character]) {
                hasLetter = YES;
            }
            if ([numberSet characterIsMember:character]) {
                hasNumber = YES;
            }
        }
    }
    
    return hasLetter && hasNumber;
}

-(NSInteger)stringWithBirthy{
    
    NSArray * array = [self componentsSeparatedByString:@"-"];
    NSDateComponents *birthComponents = [[NSDateComponents alloc] init];
    birthComponents.year = [array[0] integerValue];
    birthComponents.month = [array[1] integerValue];
    birthComponents.day = [array.lastObject integerValue];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *birthDate = [calendar dateFromComponents:birthComponents];
    NSDate *currentDate = [NSDate date];
    
    // 计算年龄
    unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *components = [calendar components:unitFlags fromDate:birthDate toDate:currentDate options:0];
    
    NSInteger age = components.year;
    NSDate *nextBirthday = [calendar dateByAddingComponents:birthComponents toDate:currentDate options:0];
    return age;

}

+ (NSAttributedString *)formatHealthInfoWithHeartRate:(NSInteger)heartRate
                                          bloodOxygen:(NSInteger)bloodOxygen
                                              temper:(CGFloat)temper
                                                  hrv:(NSInteger)hrv {
    NSMutableAttributedString *result = [[NSMutableAttributedString alloc] init];
    UIColor *nameColor = RDRGB(0xAD7D62); // 名称的颜色
    UIFont *nameFont = Medium(13); // 名称的字体大小

    NSDictionary<NSAttributedStringKey, id> *nameAttributes = @{ NSForegroundColorAttributeName: nameColor ,NSFontAttributeName: nameFont};

    if (heartRate != 0) {
        NSAttributedString *heartRateName = [[NSAttributedString alloc] initWithString:@"心率:" attributes:nameAttributes];
        [result appendAttributedString:heartRateName];
        NSString *heartRateValue = [NSString stringWithFormat:@"%ld", (long)heartRate];
        NSAttributedString *heartRateValueAttr = [[NSAttributedString alloc] initWithString:heartRateValue];
        [result appendAttributedString:heartRateValueAttr];
        [result appendAttributedString:[[NSAttributedString alloc] initWithString:@"  "]];
    }

    if (bloodOxygen != 0) {
        NSAttributedString *bloodOxygenName = [[NSAttributedString alloc] initWithString:@"血氧饱和度:" attributes:nameAttributes];
        [result appendAttributedString:bloodOxygenName];
        NSString *bloodOxygenValue = [NSString stringWithFormat:@"%ld", (long)bloodOxygen];
        NSAttributedString *bloodOxygenValueAttr = [[NSAttributedString alloc] initWithString:bloodOxygenValue];
        [result appendAttributedString:bloodOxygenValueAttr];
        [result appendAttributedString:[[NSAttributedString alloc] initWithString:@"  "]];
    }
    
    if (hrv != 0) {
        NSAttributedString *pressureName = [[NSAttributedString alloc] initWithString:@"HRV:" attributes:nameAttributes];
        [result appendAttributedString:pressureName];
        NSString *heartV = [NSString stringWithFormat:@"%ld", (long)hrv];
        NSAttributedString *pressureValueAttr = [[NSAttributedString alloc] initWithString:heartV];
        [result appendAttributedString:pressureValueAttr];
        [result appendAttributedString:[[NSAttributedString alloc] initWithString:@"  "]];
    }

    if (temper != 0) {
        NSAttributedString *temperName = [[NSAttributedString alloc] initWithString:@"体温:" attributes:nameAttributes];
        [result appendAttributedString:temperName];
        NSString *temperValue = [NSString stringWithFormat:@"%.1f", temper];
        NSAttributedString *temperValueAttr = [[NSAttributedString alloc] initWithString:temperValue];
        [result appendAttributedString:temperValueAttr];
    }
    return result;
}


+ (NSAttributedString *)formatHealthInfoWithHeartRate:(NSString *)firstString secondString:(NSString *)secondString {
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
    
    NSDictionary *firstAttributes = @{NSForegroundColorAttributeName:  RDRGB(0xAD7D62),NSFontAttributeName: Bold(14 * FMScaleX)};
    NSAttributedString *firstAttributedString = [[NSAttributedString alloc] initWithString:firstString attributes:firstAttributes];
    [attributedString appendAttributedString:firstAttributedString];
    
    NSDictionary *secondAttributes = @{NSForegroundColorAttributeName:  RDRGB(0x333333),NSFontAttributeName: Regular(13 * FMScaleX)};
    NSAttributedString *secondtAttributedString = [[NSAttributedString alloc] initWithString:secondString attributes:secondAttributes];
    [attributedString appendAttributedString:secondtAttributedString];
    
    return attributedString;;
    
    
}
@end
